#pragma once
#include <iostream>
#include <unistd.h>
#include <vector>
#include <cassert>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/fcntl.h>
#include <cassert>
#include <cstring>
#include <map>

typedef void(*fun_t)();
#define PROCESS_NUM 5
#define PATH "/home/lcl/linux/Process_communication/name_pipe_pool/mypipe"
using namespace std;

class subEp
{
public:
    subEp(string &name, pid_t id)
        : _name(name), _id(id)
    {}
public:
    string _name;
    pid_t _id;
};

vector<subEp> subs;

void downloadTask()
{
    cout << getpid() << ": 下载任务" << endl;
}
void ioTask()
{
    cout << getpid() << ": IO任务" << endl;
}

void flushTask()
{
    cout << getpid() << ": 刷新任务" << endl;
}

void loadTask(vector<fun_t>* funcMap)
{
    assert(funcMap);
    funcMap->push_back(downloadTask);
    funcMap->push_back(ioTask);
    funcMap->push_back(flushTask);
}

ssize_t recvTask(int rfd)
{
    int code = 0;
    ssize_t s = read(rfd, &code, sizeof(code));
    if (s == 4) return code;
    else if(s == 0) return 10;
    else return -1;
}

void removeFifo(vector<subEp>& subs)
{
    for(int i = 0; i < subs.size(); ++i)
    {
        int n = unlink(subs[i]._name.c_str());
        assert(n == 0);
        (void)n;
    }
}

void waitProcess(vector<subEp>& subs)
{
    for(int i = 0; i < subs.size(); ++i)
    {
        waitpid(subs[i]._id, nullptr, 0);
        cout << "wait sub process success ...: " << subs[i]._id << endl;
    }
}

void sendTask(int wfd, int taskIdx)
{
    int n = write(wfd, &taskIdx, sizeof(taskIdx));
}

